import React from 'react';
import * as PropTypes from 'prop-types';
import moment from 'moment'

import { DatePicker, List } from 'antd-mobile';

class MyDatePicker extends React.Component {
  static defaultProps = {
    format: 'YYYY',
    mode: 'year',
  }

  constructor(props) {
    super(props);

    let time;
    if ('defaultValue' in props) {
      time = props.defaultValue;
    }
    this.state = {
      time,
    };
  }

  // change
  handleChange = (data) => {
    const lastTime = this.state.time;

    const { format } = this.props;
    const time = moment(data).format(format)

    // 组件通信
    const { onChange } = this.props;
    if (onChange && time !== lastTime) {
      this.setState({
        time
      })
      onChange(time)
    }
  }

  // 格式化时间
  formatDate(date) {
    const { mode } = this.props;
    const yearStr = mode === 'month' ? moment(date).format('YYYY年MM月'): moment(date).format('YYYY年');
    return yearStr;
  }

  render() {
    const { time } = this.state;

    const { format, mode } = this.props;
    const value = moment(time, format).toDate()
    return (
      <List>
        <DatePicker
          mode={mode}
          title="选择时间"
          value={value}
          format={val => `${this.formatDate(val)}`}
          onChange={e => this.handleChange(e)}
        >
          <List.Item arrow="horizontal">选择时间：</List.Item>
        </DatePicker>
      </List>
    )
  }
}

MyDatePicker.propTypes = {
  onChange: PropTypes.func,
}

export default MyDatePicker;